<?php

namespace app\home\controller;

// 引入公共控制器
use app\common\controller\Home;

class Index extends Home
{

    protected $noNeedLogin = [
        'index',
        'login',
        'coupon',
    ];

    // 控制器初始化
    public function _initialize()
    {
        // 调用父类构造函数
        parent::_initialize();

        // 如果用助手函数调用多级模型 例如：app\common\model\Business\Business
        $this->BusinessModel = model("Business.Business");
        $this->SourceModel = model('Business.Source');
        $this->CouponModel = model('Coupon.Coupon');
        $this->ReceiveModel = model('Coupon.Receive');
        $this->SubjectModel = model('Subject.Subject');
        $this->TeacherModel = model('Subject.Teacher.Teacher');
        $this->OrderModel = model('Subject.Order');
        $this->CategoryModel = model('Subject.Category');
    }

    // 首页
    public function index()
    {
        /* 
            不带任何参数 自动定位当前操作的模板文件

            调用了think/Controller的think\View类的方法

            表示系统会按照默认规则自动定位模板文件，其规则是：
            当前模块/默认视图目录/当前控制器（小写）/当前操作（小写）.html
        */

        // 推荐列表
        $suggestList = $this->SubjectModel
            ->field(
                '
                cateid,
                MAX(id) as id,
                MAX(title) as title, 
                MAX(content) as content, 
                MAX(thumbs) as thumbs, 
                MAX(likes) as likes, 
                MAX(price) as price, 
                MAX(teacherid) as teacherid, 
                MAX(createtime) as createtime, 
                MAX(deletetime) as deletetime'
            )
            ->group('cateid')
            ->limit(5)
            // ->fetchSql(true)
            ->select();
        // var_dump($suggestList);exit;
        $subjectList = $this->SubjectModel->order('createtime desc')->limit(6)->select();
        $teacherList = $this->TeacherModel->limit(6)->select();

        // 查询教师教学课程数量

        $this->assign([
            'suggestList' => $suggestList,
            'subjectList' => $subjectList,
            'teacherList' => $teacherList,
        ]);
        return $this->view->fetch();
    }

    // 登录
    public function login()
    {
        $token = $this->request->param('token', '', 'trim');

        $businesslist = $this->BusinessModel->select();

        foreach ($businesslist as $item) {
            $busimess = md5($item['id'] . $item['mobile']);

            if ($token == $busimess) {
                // 存储token信息就将推广人存入到cookie里面,然后终止循环
                cookie('token', $token);
                break;
            }
        }

        // 是否为POST请求
        if ($this->request->isPost()) {
            // 获取请求参数param，第一个参数是获取请求字段名，第二个是默认值，第三个是执行的函数
            $mobile = $this->request->param('mobile', '', 'trim');
            $password = $this->request->param('password', '', 'trim');

            // 数据查询用户信息是否存在
            $Business = $this->BusinessModel->where('mobile', $mobile)->find();

            // 登录
            if ($Business) {
                $password = md5($password . $Business['salt']);

                if ($password == $Business['password']) {
                    $this->success('密码错误');
                    exit;
                }

                // 存储用户信息
                session('business', $Business);

                $this->success('登录成功', 'home/business/index');
            }
            // 注册
            else {

                // 密码盐
                $salt = build_randstr();

                // 密码加密
                $password = md5($password . $salt);

                $sourceid = $this->SourceModel->where('name', 'like', '%云课堂%')->value('id');

                // 组装数据并添加至数据库
                $data = [
                    'mobile' => $mobile,
                    'nickname' => $mobile,
                    'password' => $password,
                    'salt' => $salt,
                    'gender' => '0',
                    'sourceid' => $sourceid ?? null,
                    'auth' => '0',
                ];

                //判断是否有没有推荐人
                $token = empty($token) ? cookie('token') : $token;

                if (!empty($token)) {
                    $businesslist = $this->BusinessModel->select();

                    foreach ($businesslist as $item) {
                        $busimess = md5($item['id'] . $item['mobile']);

                        if ($token == $busimess) {
                            $data['parentid'] = $item['id'];
                            break;
                        }
                    }
                }

                $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

                if ($result === false) {
                    // getError => 返回模型的错误信息
                    $this->error($this->BusinessModel->getError());
                    exit;
                } else {
                    $this->success('注册成功', 'home/business/index');
                    exit;
                }
            }
        }
        return $this->view->fetch();
    }

    // 退出登录
    public function logout()
    {
        // 删除（当前作用域）
        session('business', null);
        $this->error('退出成功', 'home/index/login');
        exit;
    }

    // 优惠券
    public function coupon()
    {
        if ($this->request->isPost()) {
            // 获取页码
            $page = $this->request->param('page', 1, 'intval');
            // 每页显示数量
            $limit = 10;
            // 计算偏移量
            $offset = ($page - 1) * $limit;

            // 组装响应数据
            $data = [
                'list' => [],
                'count' => 0,
            ];

            // 查询优惠券列表
            $couponList = $this->CouponModel
                ->limit($offset, $limit)
                ->order('id desc')->select();

            // var_dump($couponList[0]['endtime']);
            // exit;

            // 获取用户信息
            $business = session('business') ? session('business') : [];

            $couponData = [];
            // 提取查询结果的data字段
            foreach ($couponList as $coupon) {

                // 判断用户是否已登录
                $result = null;
                if ($business) {
                    // 查询优惠券是否已领取
                    $result = $this->ReceiveModel
                        ->where('cid', $coupon['id'])
                        ->where('busid', $business['id'])
                        ->find();
                }
                // 组装领取状态字段
                if ($result) {
                    $coupon['receive_text'] = '已领取';
                } else {
                    $coupon['receive_text'] = null;
                }
                $couponData[] = $coupon;
            }

            // 组装数据
            if ($couponList) {
                $data['list'] = $couponData;
                $data['count'] = $this->CouponModel->count();


                // 响应数据
                $this->success('', '', $data);
            } else {
                // 响应数据
                $this->error('暂无数据', '', $data);
            }
        }

        return $this->view->fetch();
    }

    // 课程榜单
    public function ranking()
    {
        if ($this->request->isPost()) {
            $page = $this->request->param('page', 1, 'trim');

             // COUNT(subid) as count 统计每个 subid 的订单数
            $fields =
                'subid,
                COUNT(subid) as count,
                MAX(order.id) as order_id,
                MAX(busid) as busid,
                MAX(total) as total,
                MAX(code) as code,
                MAX(order.createtime) as order_createtime,
                MAX(order.deletetime) as order_deletetime,
                MAX(pay) as pay, 
                MAX(subject.id) as subject_id,
                MAX(subject.title) as subject_title,
                MAX(subject.content) as subject_content,
                MAX(subject.thumbs) as subject_thumbs,
                MAX(subject.likes) as subject_likes,
                MAX(subject.price) as subject_price,
                MAX(subject.cateid) as subject_cateid,
                MAX(subject.teacherid) as subject_teacherid,
                MAX(subject.createtime) as subject_createtime, 
                MAX(subject.deletetime) as subject_deletetime';

            $list = $this->OrderModel->field($fields)->with(['subject'])->group('subid', 'busid', 'order.id')->order('total', 'desc')->page("$page, 10")->select();
            // var_dump($list);
            // exit;

            // 总数
            $count = $this->OrderModel->with(['subject'])->field($fields)->group('subid', 'busid', 'order.id')->select();
            $count = count($count);

            if ($list) {

                foreach ($list as $item) {
                    $cateid = isset($item['subject']['cateid']) ? $item['subject']['cateid'] : 0;
                    $category = $this->CategoryModel->where('id', $cateid)->value('name');
                    $item['category'] = $category ? $category : '未知分类';

                    $teacherid = isset($item['subject']['teacherid']) ? $item['subject']['teacherid'] : 0;
                    $teacher =  $this->TeacherModel->where('id', $teacherid)->value('name');
                    $item['teacher'] = $teacher ? $teacher : '暂无授课老师';
                }

                $data = [
                    'count' => $count,
                    'list' => $list
                ];

                $this->success('', '', $data);
            } else {
                $this->error('暂无更多数据');
            }
        }
        return $this->view->fetch();
    }
}
